package com.luo.ssm.controller;

import com.luo.ssm.entity.SysUser;
import com.luo.ssm.service.SysUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.text.SimpleDateFormat;
import java.util.Date;

/**
 * @author : luocheng
 * @date : Created in 2021/8/28 16:45
 * @description : 用户模块控制器
 */
@Controller
@RequestMapping("/userManage")
public class SysUserController {
    @Autowired
    private SysUserService sysUserService;

    /**
     * 登录判断
     * @param sysUser
     * @param code
     * @param session
     * @param request
     * @return
     */
    @PostMapping("/login")
    public String login(SysUser sysUser, @RequestParam("code") String code, HttpSession session, HttpServletRequest request){
        //先判断验证码是否正确，忽略大小写
        if (!String.valueOf(session.getAttribute("code")).equalsIgnoreCase(code)){
            //验证码错误，请求中存入错误信息，跳转到登录界面
            request.setAttribute("errorMsg","验证码错误");
            return "login";
        }else {
            //验证码正确，在判断用户名和密码是否正确
            SysUser login = sysUserService.login(sysUser);
            if (null==login){
                //若查询的用户为空,请求中存入错误信息，跳转到登录界面
                request.setAttribute("errorMsg","用户名或密码错误");
                return "login";
            }else {
                //若查询用户信息正确，session中存入用户信息,跳转到主界面
                session.setAttribute("user",login);
                //存储一个服务器上的登录时间
                session.setAttribute("loginTime",new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date()));
                return "main/index";
            }
        }
    }

    /**
     * 用户退出系统
     * @param session
     * @return
     */
    @GetMapping("/logout")
    public String logout(HttpSession session){
        //销毁当前session，并重定向到登录界面
        session.invalidate();
        return "redirect:/index.html";
    }

    /**
     * 用户修改密码
     * @param sysUser
     * @param session
     * @return
     */
    @RequestMapping("/updatePassword")
    public String updatePassword(SysUser sysUser,HttpSession session,@RequestParam("newpass") String newpass){
        sysUser.setUpwd(newpass);
        int i = sysUserService.updatePassword(sysUser);
        //销毁当前session
        session.invalidate();
        //重定向到登录界面
        return "redirect:/index.html";
    }
}
